import React, { useState, useEffect, useContext  } from 'react';
import { getRoleList, addRole, updateRole, getRole, delRole  } from '../../../api/system/role'
import { Table, Tag, Button, Popconfirm, message,Space, Pagination, Form, Input, Select,DatePicker, Modal, Row, Col, TreeSelect, Radio,Tree,InputNumber    } from 'antd';
import { DictContext } from '../../../context/context';
import DictTag from '../../../components/DictTag';
import { SearchOutlined , RedoOutlined, PlusOutlined, EditOutlined, DeleteOutlined} from '@ant-design/icons';
import { treeselect as menuTreeselect ,roleMenuTreeselect } from "../../../api/system/menu";

function Role() {
  const [roleData, setRoleData] = useState([]);
  const { useDict, addDateRange } = useContext(DictContext);
  const { sys_normal_disable } = useDict('sys_normal_disable');
  const [queryParams, setQueryParams] = useState({pageSize:4, pageNum:1});
  const [total, setTotal] = useState(0);
  const { RangePicker } = DatePicker;
  const [searchForm] = Form.useForm();
  const [addForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [title, setTitle] = useState('');
  const [menuOptions, setMenuOptions] = useState([]);
  const [single, setSingle] = useState(true);
  const [multiple, setMultiple] = useState(true);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [ids, setIds] = useState([]);

  const columns =[
    {
      title: '角色编号',
      dataIndex: 'roleId',
      key: 'roleId',
    },{
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName',
    },{
      title: '权限字符',
      dataIndex: 'roleKey',
      key: 'roleKey',
    },{
      title: '显示顺序',
      dataIndex: 'roleSort',
      key: 'roleSort',
    },{
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (text, record) => {
        return (<DictTag dictType="sys_normal_disable" value={text} options={sys_normal_disable} ></DictTag>)
      }
    },{
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) =>
          <Space size="middle">
          <Button type='link' onClick={() => handleUpdate(record)}>修改</Button>
          <Popconfirm
            title="删除确认"
            description={`是否确认删除用户编号为 ${record.roleId} 的数据项？`}
            onConfirm={() => handleDelete(record)}
            onCancel={delCancel}
            okText="确定"
            cancelText="取消"
          >
          <Button type='link'>删除</Button>
          </Popconfirm>
          </Space>
    }
  ];

  const handleUpdate = (record) => {
    console.log(record);
    const roleId = record.roleId || ids;

    getMenuTreeSelect();
    const roleMenu = getRoleTreeSelect(roleId);
    getRole(roleId).then(res => {
      console.log('====getRole=======',res);
      addForm.setFieldsValue(res.data);
      roleMenu.then(res => {
        console.log('====roleMenu=======',res);
        addForm.setFieldsValue({menuIds: res.checkedKeys});
      })
    });

    setOpen(true);
    setTitle('修改角色');

  }

  const handleDelete = (record) => {
    console.log(record);
    const roleId = record.roleId || ids;
    delRole(roleId).then(res => {
      message.success('删除成功');
      getList();
    })
  }

  const delCancel = () => {
    console.log('cancel');
  }

  useEffect(() => {
    setLoading(true);
    getList();  
  },[queryParams])

  const onFinish = (values) => {
    //console.log('Success:', values);
    setQueryParams( preState => ({
      ...preState,
      ...values,
    }));
  }

  
function getList() {
  getRoleList(addDateRange(queryParams, queryParams.timeRange)).then(res => {
    //console.log(res.rows);
    setRoleData(res.rows);
    setLoading(false);
    setTotal(res.total);
  })
}

const handleOk = () => {
  setOpen(false);
  console.log('====role handleok====',addForm.getFieldValue());
  if(addForm.getFieldValue().roleId  == undefined){
    addRole(addForm.getFieldValue()).then(res => {
      message.success('添加成功');
      getList();
    })
  }else{
    updateRole(addForm.getFieldValue()).then(res => {
      message.success('修改成功');
      getList();
    })
  }
}

const handleCancel = () => {
  setOpen(false);
}

  const handleAdd = () => {
    getMenuTreeSelect();
    setOpen(true);
    setTitle('新增角色');
  }

  // 获取菜单树选择
  function getMenuTreeSelect() {
    // 调用menuTreeselect函数，并返回一个Promise对象
    menuTreeselect().then(response => {
        // 将返回的数据赋值给menuOptions的value属性
        //console.log(response);
        setMenuOptions(response.data);
    });
}

function getRoleTreeSelect(roleId) {
    return roleMenuTreeselect(roleId).then(response => {
        setMenuOptions(response.menus);
        return response;
    });
}

const onChangeTreeSelect = (value, label, extra) => {
    //console.log('onchange', value, label, extra);
}

const onPageChange = (pagination) => {
  //console.log(pagination);
  setQueryParams( preState => ({
    ...preState,
    pageNum: pagination.current,
    pageSize: pagination.pageSize,
  }));
}

const onSelectChange = newSelectedRowKeys => {
  //console.log('selectedRowKeys changed: ', newSelectedRowKeys);
  setSelectedRowKeys(newSelectedRowKeys);
  setSingle(newSelectedRowKeys.length != 1) ;
  setMultiple(!newSelectedRowKeys.length);
  setIds(newSelectedRowKeys);
};
const rowSelection = {
  selectedRowKeys,
  onChange: onSelectChange,
};

  return (
    <div style={{
      height: '100%',
    }}>
      <Row gutter={[16, 16]} style={{marginBottom: '16px'}}>
        <Col span={24}>
          <Form layout="inline" form={searchForm} onFinish={onFinish}>
            <Form.Item label="角色名称" name="roleName">
              <Input placeholder="请输入角色名称"  allowClear/>
            </Form.Item>
            <Form.Item label="状态" name="status">
              <Select placeholder="请选择状态" options={sys_normal_disable.value}  allowClear/>
            </Form.Item>
            <Form.Item label="创建时间" name="timeRange">
              <RangePicker showTime format="YYYY-MM-DD HH:mm:ss"/>
            </Form.Item>
            <Form.Item>
              <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>搜索</Button>
              <Button type="default" icon={<RedoOutlined />} onClick={() => searchForm.resetFields()}>重置</Button>
              </Space>
            </Form.Item>
          </Form>
        </Col>
      </Row>
      <Row gutter={[16, 16]} style={{marginBottom: '16px'}}>
        <Col span={24}>
        <Space>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>新增</Button>
          <Button type="primary" icon={<EditOutlined />} disabled={single} onClick={handleUpdate}>修改</Button>
          <Button type="primary" icon={<DeleteOutlined />} disabled={multiple} onClick={handleDelete}>删除</Button>
          </Space>
        </Col>
      </Row>
      <Row gutter={ [16, 16]}>
        <Col span={24}>
        <Table dataSource={roleData} rowSelection={rowSelection} loading={loading} columns={columns} pagination={{ pageSize: queryParams.pageSize, current: queryParams.pageNum ,showQuickJumper: true, pageSizeOptions: [3, 5, 10, 20], showSizeChanger: true, total: total, showTotal: total => `共 ${total} 条`}} rowKey={record => record.roleId} onChange={onPageChange}></Table>
        </Col>
      </Row>
      <Modal open={open} title={title} onOk={handleOk} onCancel={handleCancel}>
        <Form form={addForm}>
          <Form.Item label="角色名称" name="roleName">
            <Input placeholder="请输入角色名称" />
          </Form.Item>
          <Form.Item label="权限字符" name="roleKey">
            <Input placeholder="请输入权限字符" />
          </Form.Item>
          <Form.Item label="显示顺序" name="roleSort">
            <InputNumber  placeholder="请输入显示顺序" />
          </Form.Item>
          <Form.Item label="状态" name="status">
            <Select placeholder="请选择状态" options={sys_normal_disable.value} />
          </Form.Item>
          <Form.Item label="菜单权限" name="menuIds">
            <TreeSelect treeData={menuOptions} placeholder="请选择菜单权限" 
                treeCheckable={true} fieldNames={{ label: 'label', value: 'id', children: 'children' }} 
                onChange={ onChangeTreeSelect}
                allowClear/>
          </Form.Item>
          <Form.Item label="备注" name="remark">
            <Input.TextArea placeholder="请输入备注" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default Role;